//
//  DBHelper.m
//  TravelGuideMdd
//
//  Created by BigPolarBear on 13-5-20.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "DBHelper.h"

@implementation DBHelper{}

#pragma mark ------ 辅助方法

+(NSString*)sqlInArray:(NSArray*)array
{
    NSMutableString* sql = [[NSMutableString alloc]initWithCapacity:0];

    for (int iCnt = 0; iCnt < array.count; iCnt++) {
        // 这里是把所有元素都转成字符串，用引号引起来，其实对于数值类型的不需要
        NSString* elem = [NSString stringWithFormat:@"%@",[array objectAtIndex:iCnt]];
        if (iCnt == 0) {
            [sql appendString:[DBHelper stringWithQuotes:elem]];
        }else{
            [sql appendFormat:@",%@",[DBHelper stringWithQuotes:elem]];
        }
    }
    
    return sql;
}


+(NSString*)stringWithQuotes:(NSString*)str
{
    if (str.length == 0) {
        return @"''";
    }
    NSString *sql = [NSString stringWithFormat:@"'%@'"
                     ,[str stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
    return sql;
}


+(BOOL)isBaseColumnName:(NSString*)columnName
{
    if ([columnName isEqualToString:kTableColumn_base_c_id]
        || [columnName isEqualToString:kTableColumn_base_c_json]
        || [columnName isEqualToString:kTableColumn_base_c_utime]
        || [columnName isEqualToString:kTableColumn_base_c_ctime]) {
        return YES;
    }else{
        return NO;
    }
}





#pragma mark ------ 执行SQL脚本预定义


#pragma mark
+(BOOL)executeNoteCacheCreateDatabase:(FMDatabase*)db
{
    NSString * sql = @"create table if not exists t_daily("
    @"c_id text primary key"
    @",c_json text"
    @",c_type text"
    @",c_utime TIMESTAMP DEFAULT (datetime('now','localtime'))"
    @",c_ctime TIMESTAMP DEFAULT (datetime('now','localtime'))"
    @",c_editid text"
    @");";
    
    return [db executeUpdate:sql];
}

+(BOOL)executeNoteDeleteForKey:(NSString*)key database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:@" DELETE FROM %@ WHERE c_id = %@"
                     ,kTableName_Daily
                     ,[DBHelper stringWithQuotes:key]];
    
    return [db executeUpdate:sql];
}



+(BOOL)executeNoteSetValue:(NSString*)value forKey:(NSString*)key database:(FMDatabase*)db
{
    BOOL success = YES;
    
    NSString* sql = [NSString stringWithFormat:
                     @" INSERT OR IGNORE INTO %@(c_key,c_ctime)"
                     @" VALUES (%@, datetime('now','localtime'));"
                     , kTableName_Daily
                     , [DBHelper stringWithQuotes:key]
                     ];
    success = success && [db executeUpdate:sql];
    
    sql = [NSString stringWithFormat:
           @" UPDATE %@ SET c_json = %@,c_utime =(datetime('now','localtime'))"
           @" WHERE c_editid = %@"
           , kTableName_Daily
           , [DBHelper stringWithQuotes:value]
           , [DBHelper stringWithQuotes:key]
           ];
    success = success && [db executeUpdate:sql];
    
    return success;
}


+(FMResultSet*)executeNoteSelectValueForKey:(NSString*)key database:(FMDatabase *)db
{
    NSString* sql = [NSString stringWithFormat:
                     @" SELECT c_json from %@"
                     @" WHERE c_editid = %@"
                     ,kTableName_Daily
                     ,[DBHelper stringWithQuotes:key]];
    
    return [db executeQuery:sql];
}

#pragma mark 缓存表相关

+(BOOL)executeCacheCreateDatabase:(FMDatabase*)db
{
    NSString* sql = @"create table if not exists "
    kTableName_Cache
    @"("
    @"c_key text primary key"
    @",c_value text"
    @",c_utime TIMESTAMP DEFAULT (datetime('now','localtime'))"
    @",c_ctime TIMESTAMP DEFAULT (datetime('now','localtime'))"
    @")";
    
    return [db executeUpdate:sql];
}

+(BOOL)executeCacheDeleteForKey:(NSString*)key database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:@" DELETE FROM %@ WHERE c_key = %@"
                     ,kTableName_Cache
                     ,[DBHelper stringWithQuotes:key]];
    
    return [db executeUpdate:sql];
}

+(BOOL)executeCacheSetValue:(NSString*)value forKey:(NSString*)key database:(FMDatabase*)db
{
    BOOL success = YES;
    
    NSString* sql = [NSString stringWithFormat:
                     @" INSERT OR IGNORE INTO %@(c_key,c_ctime)"
                     @" VALUES (%@, datetime('now','localtime'));"
                     , kTableName_Cache
                     , [DBHelper stringWithQuotes:key]
                     ];
    success = success && [db executeUpdate:sql];
    
    sql = [NSString stringWithFormat:
                     @" UPDATE %@ SET c_value = %@,c_utime =(datetime('now','localtime'))"
                     @" WHERE c_key = %@"
                     , kTableName_Cache
                     , [DBHelper stringWithQuotes:value]
                     , [DBHelper stringWithQuotes:key]
                     ];
    success = success && [db executeUpdate:sql];
    
    return success;
}


+(FMResultSet*)executeCacheSelectValueForKey:(NSString*)key database:(FMDatabase *)db
{
    NSString* sql = [NSString stringWithFormat:
                     @" SELECT c_value from %@"
                     @" WHERE c_key = %@"
                     ,kTableName_Cache
                     ,[DBHelper stringWithQuotes:key]];
    
    return [db executeQuery:sql];
}
+(FMResultSet*)executeCacheSelectForKey:(NSString*)key database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:
                     @" SELECT * from %@"
                     @" WHERE c_key = %@"
                     ,kTableName_Cache
                     ,[DBHelper stringWithQuotes:key]];

    return [db executeQuery:sql];
}

+(BOOL)executeCacheDelete:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:
                     @" DELETE from %@"
                     ,kTableName_Cache
                     ];
    
    [db executeQuery:sql];
    return YES;
}

+(FMResultSet*)executeCacheSelectForKeyPrefix:(NSString*)keyPrefix database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:
                     @" SELECT * from %@"
                     @" WHERE c_key like %@"
                     @" ORDER BY %@"
                     ,kTableName_Cache
                     ,[DBHelper stringWithQuotes:[NSString stringWithFormat:@"%@%%",keyPrefix]]
                     ,kTableColumn_base_c_utime];
    
    return [db executeQuery:sql];
}

#pragma mark 查询脚本执行


+(FMResultSet*)executeSelectTable:(NSString*)tableName
                            c_ids:(NSArray*)c_ids
                         database:(FMDatabase*)db
{    
    NSMutableString* sql = [[NSMutableString alloc]initWithCapacity:0];
    
    if (c_ids) {
        [c_ids enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString* c_id = obj;
            if (idx > 0) {
                [sql appendString:@" UNION "];
            }
            
            [sql appendFormat:@" SELECT * FROM %@ WHERE %@ =%@"
             ,tableName
             ,kTableColumn_base_c_id
             ,[DBHelper stringWithQuotes:c_id]
             ];
        }];
    }
    
    return [db executeQuery:sql];
}


+(FMResultSet*)executeSelectTable:(NSString*)tableName
                      columnNames:(NSArray*)columnNames
                       filterDict:(NSDictionary*)filterDict
                          orderBy:(NSString*)orderByColumnName
                             desc:(BOOL)desc
                         database:(FMDatabase*)db
{
    NSMutableString* sql = [[NSMutableString alloc]initWithCapacity:0];
    
    [sql appendString:@"SELECT "];
    if (columnNames.count > 0) {
        
        [columnNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx > 0) {
                [sql appendString:@","];
            }
            [sql appendString:obj];
        }];
    }else{
        [sql appendString:@" * "];
    }

    [sql appendFormat:@" FROM %@ ",tableName];
    
    if (filterDict.count > 0) {
        [sql appendString:@" WHERE "];
        [filterDict.allKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString* key = obj;
            NSString* value = [filterDict objectForKey:key];
            if (idx > 0) {
                [sql appendString:@" and "];
            }
            
            [sql appendFormat:@"%@ = %@",key,[DBHelper stringWithQuotes:value]];
        }];
    }
    
    if (orderByColumnName.length > 0) {
        [sql appendFormat:@" ORDER BY %@",orderByColumnName];
        if (desc) {
            [sql appendString:@" DESC "];
        }
    }
    
    return [db executeQuery:sql];
}


+(NSInteger)executeCountTable:(NSString*)tableName
                   filterDict:(NSDictionary*)filterDict
                     database:(FMDatabase*)db
{
    NSMutableString* sql = [[NSMutableString alloc]initWithCapacity:0];
        
    [sql appendFormat:@"SELECT COUNT(*) FROM %@ ",tableName];
    
    if (filterDict.count > 0) {
        [sql appendString:@" WHERE "];
        [filterDict.allKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString* key = obj;
            NSString* value = [filterDict objectForKey:key];
            if (idx > 0) {
                [sql appendString:@" and "];
            }
            
            [sql appendFormat:@"%@ = %@",key,[DBHelper stringWithQuotes:value]];
        }];
    }
    
    FMResultSet* result = [db executeQuery:sql];
    NSInteger count = 0;
    while ([result next]) {
        count = [result intForColumnIndex:0];
        break;
    }

    return count;
}


#pragma mark 删除脚本执行
+(BOOL)executeDeleteTable:(NSString*)tableName
               filterDict:(NSDictionary*)filterDict
                 database:(FMDatabase*)db
{
    NSMutableString* sql = [[NSMutableString alloc]initWithCapacity:0];
    
    [sql appendFormat:@"DELETE FROM %@ ",tableName];
    
    if (filterDict.count > 0) {
        [sql appendString:@" WHERE "];
        [filterDict.allKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString* key = obj;
            NSString* value = [filterDict objectForKey:key];
            if (idx > 0) {
                [sql appendString:@" and "];
            }
            
            [sql appendFormat:@"%@ = %@",key,[DBHelper stringWithQuotes:value]];
        }];
    }
    
    return [db executeUpdate:sql];
}

+(BOOL)executeDeleteTable:(NSString*)tableName
                 database:(FMDatabase*)db
{
    NSString* sql = [NSString stringWithFormat:@"DELETE FROM %@ ",tableName];
    
    return [db executeUpdate:sql];
}

#pragma mark 插入与更新脚本执行

+(BOOL)executeInsertTable:(NSString*)tableName
                     c_id:(NSString*)c_id
                   c_json:(NSString*)c_json
    withColumnKeyValueDict:(NSDictionary*)dict
                    database:(FMDatabase*)db
{
    if (c_id.length == 0) {
        return NO;
    }
    
    NSMutableString* sqlColumnName = [NSMutableString stringWithFormat:@"%@,%@,%@,%@"
                                      ,kTableColumn_base_c_id
                                      ,kTableColumn_base_c_json
                                      ,kTableColumn_base_c_utime
                                      ,kTableColumn_base_c_ctime];
    
    NSMutableString* sqlColumnValue = [NSMutableString stringWithFormat:@"%@,%@,%@,%@"
                                       ,[DBHelper stringWithQuotes:c_id]
                                       ,[DBHelper stringWithQuotes:c_json]
                                       ,@"datetime('now','localtime')"
                                       ,@"datetime('now','localtime')"];

    if (dict) {
        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            NSString* columnName = key;
            NSString* columnValue = obj;
            
            // 如果是基础字段则忽略
            if (![[self class] isBaseColumnName:columnName]) {
                [sqlColumnName appendString:@","];
                [sqlColumnValue appendString:@","];
                
                [sqlColumnName appendString:columnName];
                [sqlColumnValue appendString:[DBHelper stringWithQuotes:columnValue]];                
            }
        }];
    }

    
    NSString* sql = [NSString stringWithFormat:@"INSERT OR IGNORE INTO %@ (%@) VALUES(%@);"
                     ,tableName
                     ,sqlColumnName
                     ,sqlColumnValue
                     ];
    
//#ifdef DEBUG
//    if (![tableName isEqualToString:kTableName_Book]
//        && ![tableName isEqualToString:kTableName_Book]) {
//        NSLog(@"sql:%@",sql);
//    }
//#endif
    
    return [db executeUpdate:sql];
}

+(BOOL)executeUpdateTable:(NSString*)tableName
                     c_id:(NSString*)c_id
                   c_json:(NSString*)c_json
    withColumnKeyValueDict:(NSDictionary*)dict
                    database:(FMDatabase*)db
{
    if (c_id.length == 0) {
        return NO;
    }
    
    NSMutableString* sqlSet = [NSMutableString stringWithFormat:@"%@ = %@, %@ = %@"
                               ,kTableColumn_base_c_utime
                               ,@"datetime('now','localtime')"
                               ,kTableColumn_base_c_json
                               ,[DBHelper stringWithQuotes:c_json]];
    
    if (dict) {
        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            NSString* columnName = key;
            NSString* columnValue = obj;
            
            // 如果是基础字段则忽略
            if (![[self class] isBaseColumnName:columnName]) {
                [sqlSet appendFormat:@", %@ = %@",columnName,[DBHelper stringWithQuotes:columnValue]];
            }
        }];
    }

    
    NSString* sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@ = %@;"
                     ,tableName
                     ,sqlSet
                     ,kTableColumn_base_c_id
                     ,[self stringWithQuotes:c_id]
                     ];
    
    return [db executeUpdate:sql];
}

+(BOOL)executeUpdateTable:(NSString*)tableName
                     c_id:(NSString*)c_id
   withColumnKeyValueDict:(NSDictionary*)dict
                 database:(FMDatabase*)db
{
    if (c_id.length == 0 || dict.count == 0) {
        return NO;
    }
    
    
    NSMutableString* sqlSet = [NSMutableString stringWithFormat:@"%@ = %@"
                               ,kTableColumn_base_c_utime
                               ,@"datetime('now','localtime')"
                               ];
    
    if (dict) {
        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            NSString* columnName = key;
            NSString* columnValue = obj;
            
            // 如果是基础字段则忽略
            if (![[self class] isBaseColumnName:columnName]) {
                [sqlSet appendFormat:@", %@ = %@",columnName,[DBHelper stringWithQuotes:columnValue]];
            }
        }];
    }
    
    
    NSString* sql = [NSString stringWithFormat:@"UPDATE %@ SET %@ WHERE %@ = %@;"
                     ,tableName
                     ,sqlSet
                     ,kTableColumn_base_c_id
                     ,[self stringWithQuotes:c_id]
                     ];
    
    return [db executeUpdate:sql];
}

+(BOOL)executeInsertOrUpdateTable:(NSString*)tableName
                             c_id:(NSString*)c_id
                           c_json:(NSString*)c_json
            withColumnKeyValueDict:(NSDictionary*)dict
                         database:(FMDatabase*)db
{
    // todo 如果可以确保传入的是字符串，则下面这行代码可以去掉
    c_id = [NSString stringWithFormat:@"%@",c_id];
    
    BOOL success = YES;
    success = success && [self executeInsertTable:tableName
                                             c_id:c_id
                                           c_json:c_json
                           withColumnKeyValueDict:dict
                                         database:db];
    
    success = success && [self executeUpdateTable:tableName
                                             c_id:c_id
                                           c_json:c_json
                           withColumnKeyValueDict:dict
                                         database:db];
    return success;
}

+(BOOL)executeDeleteTable:(NSString*)tableName
                    c_ids:(NSArray*)c_ids
                 database:(FMDatabase*)db
{
    if (c_ids.count == 0) {
        return YES;
    }
    
    NSString* sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE %@ in (%@)"
                     ,tableName
                     ,kTableColumn_base_c_id
                     ,[self sqlInArray:c_ids]];
    return [db executeUpdate:sql];
}

#pragma mark 定制查询
/** 根据关键词搜索，按拼音排序 */
+(FMResultSet*)executeSelectMddSimpleByKeyword:(NSString*)keyword
                                      database:(FMDatabase*)db
{
    NSMutableString* sql = [NSMutableString stringWithFormat:@"SELECT * FROM %@ ",kTableName_Mdd_Simple];
    if (keyword.length > 0) {
        [sql appendFormat:@" WHERE %@ like '%@%%' ",kTableColumn_mdd_simple_name,keyword];
        [sql appendFormat:@"OR %@ like '%@%%' ",kTableColumn_mdd_simple_pinyin_f,keyword];
        [sql appendFormat:@"OR %@ like '%@%%' ",kTableColumn_mdd_simple_pinyin_s,keyword];
    }
    
    [sql appendFormat:@" ORDER BY %@,%@",kTableColumn_mdd_simple_pinyin_s,kTableColumn_mdd_simple_pinyin_f];
    
    return [db executeQuery:sql];
}

/** 根据类型，按拼音排序*/
+(FMResultSet*)executeSelectMddSimpleByTypeRegion:(NSString*)type_region
                                         database:(FMDatabase*)db
{
    NSMutableString* sql = [NSMutableString stringWithFormat:@"SELECT * FROM %@ ",kTableName_Mdd_Simple];
    if (type_region) {
        [sql appendFormat:@" WHERE %@ = '%@' ",kTableColumn_mdd_simple_type_region,type_region];
    }
    
    [sql appendFormat:@" ORDER BY %@,%@",kTableColumn_mdd_simple_pinyin_s,kTableColumn_mdd_simple_pinyin_f];
    
    return [db executeQuery:sql];
}




#pragma mark 城市信息数据库操作


+(void)insertCityInfoWithCityJson:(NSString *)jsonString andCityId:(NSString *)cityId andState:(NSString *)state withDB:(FMDatabase *)db andCurrentCount:(NSInteger)currentCOunt andAllCount:(NSInteger)allCount{
    [db open];
    NSString *currentStr=[NSString stringWithFormat:@"%ld",(long)currentCOunt];
    NSString *allStr=[NSString stringWithFormat:@"%ld",(long)allCount];

 if( [db executeUpdate:@"insert into t_city_info(c_json, type, state,currentCount,allCount) values(?, ?, ?,?,?)",jsonString,cityId,state,currentStr,allStr])
 {
     NSLog(@"insert success");
 }
    [db close];
}

+(NSMutableArray *)selectAllCityInfoFromDatabase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_city_info"];
    while ([res next]) {
        
        NSString *string=[res stringForColumn:@"c_json"];
        [array addObject:string];
    }
    [db close];
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for (int i=(int)array.count-1;i>=0;i--){
        NSString *str=array[i];
        [arr addObject:str];
    }
    return arr;
}

+(NSMutableArray *)getDownloadCountArrayWithDataBase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_city_info"];
    while ([res next]) {
        
        NSString *string=[res stringForColumn:@"currentCount"];
        [array addObject:string];
    }
    [db close];
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for (int i=(int)array.count-1;i>=0;i--){
        NSString *str=array[i];
        [arr addObject:str];
    }
    return arr;
}

+(void)updateDownloadStateWithCityId:(NSString *)cityId andDB:(FMDatabase *)db andState:(NSString *)state{
    [db open];
    [db executeUpdate:@"update t_city_info set state=? where type=?",state,cityId];
    [db close];
}


+ (void)updatedownloadCountWithCityId:(NSString *)cityId andDownloadCount:(NSString *)count andDatabase:(FMDatabase *)db{
    [db open];
    [db executeUpdate:@"update t_city_info set currentCount=? where type=?",count,cityId];
    [db close];
}

+ (NSMutableArray *)selectAllCityIdFromDatabase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_city_info"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"type"];
        [array addObject:string];
    }
    [db close];
    
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for (int i=(int)array.count-1;i>=0;i--){
        NSString *str=array[i];
        [arr addObject:str];
    }
    return arr;
}

+ (NSString *)getDownloadStateWithCityId:(NSString *)cityId andDatabase:(FMDatabase *)db{
    [db open];
 FMResultSet *s=[db executeQuery:@"select * from t_city_info where type=?",cityId];
    NSString *state;
    while ([s next]) {
        state=[s stringForColumn:@"state"];
    }
    [db close];
    
    return state;
}

+ (NSMutableArray *)getAllCountArrayWithDataBase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_city_info"];
    while ([res next]) {
        
        NSString *string=[res stringForColumn:@"allCount"];
        [array addObject:string];
    }
    [db close];
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for (int i=(int)array.count-1;i>=0;i--){
        NSString *str=array[i];
        [arr addObject:str];
    }
    return arr;
}

+ (NSMutableArray *)getDownloadStateWithDatabase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_city_info"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"state"];
        [array addObject:string];
    }
    [db close];
    
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    for (int i=(int)array.count-1;i>=0;i--){
        NSString *str=array[i];
        [arr addObject:str];
    }
    return arr;
}

+ (NSString *)getJsonStringWithCityId:(NSString *)cityId andDatabase:(FMDatabase *)db{
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_city_info where type=?",cityId];
    NSString *state;
    while ([s next]) {
        state=[s stringForColumn:@"c_json"];
    }
    [db close];
    return state;
}


+ (NSString *)getDownloadCountWithCityId:(NSString *)cityId andDatabase:(FMDatabase *)db{
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_city_info where type=?",cityId];
    NSString *currentCount;
    while ([s next]) {
        currentCount=[s stringForColumn:@"currentCount"];
    }
    [db close];
    return currentCount;
}
+(void)deleteItemWithItemId:(NSString *)cityId withDatabase:(FMDatabase *)db
{
    [db open];
    
    [db executeUpdate:@"delete from t_city_info where type=?",cityId];
    
    [db close];
}

#pragma mark - 食记本地操作

+(void)insertDailyJsonString:(NSString *)jsonString andKey:(NSString *)key type:(NSString *)type WithDatabase:(FMDatabase *)db{
    [db open];
    
    if( [db executeUpdate:@"insert into t_daily(c_editid,c_json,c_type) values(?,?,?)",key,jsonString,type])
    {
        NSLog(@"insert success");
    }
    [db close];
}

+(BOOL) deleteNoteItem:(NSString*) dbid withDatabase:(FMDatabase*)db
{
    [db open];
    
    BOOL isSuccess = [db executeUpdate:@"delete from t_daily where c_editid=?",dbid];
    [db close];
    return isSuccess;
}

+ (NSString *)getTypeStringWithNoteId:(NSString *)noteId andDataBase:(FMDatabase *)db{
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_daily where c_editid=?",noteId];
    NSString *jsString;
    while ([s next]) {
        jsString=[s stringForColumn:@"c_type"];
    }
    [db close];
    return jsString;
}

+ (NSString *)getJsonStringWithIndex:(NSString *)indexSring andDataBase:(FMDatabase *)db{
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_daily where c_editid=?",indexSring];
    NSString *jsString;
    while ([s next]) {
        jsString=[s stringForColumn:@"c_json"];
    }
    [db close];
    return jsString;
}

+ (NSMutableArray *)getDataCountWith:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_daily"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"c_editid"];
        if (string)
        [array addObject:string];
    }
    [db close];
    return array;
}

+ (NSMutableArray *)getAllJsonIdWith:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_daily"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"c_editid"];
        [array addObject:string];
    }
    [db close];
    return array;
}


+ (NSMutableArray *)getAllJsonStringWith:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_daily"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"c_json"];
        if (string)
        [array addObject:string];
    }
    [db close];
    return array;
}

+(NSString *)getJSonCurrentIDwithjSONWithJsonString:(NSString *)jsonString andDataBase:(FMDatabase *)db{
    NSString *noteId=nil;
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_daily where c_json=?",jsonString];
    while ([s next]) {
        noteId=[s stringForColumn:@"c_editid"];
    }
    [db close];
    return noteId;
}


+ (void)updatedownJsonStringWithCurrentId:(NSString *)currentId andNewJsonString:(NSString *)newString andDataBase:(FMDatabase *)db{
    [db open];
    [db executeUpdate:@"update t_daily set c_json=? where c_editid=?",newString,currentId];
    [db close];
}

#pragma - mark - 清单餐厅本地
+(void)insertTraveListRest:(NSString *)jsonString andKey:(NSString *)key WithDatabase:(FMDatabase *)db{
    [db open];
    if( [db executeUpdate:@"insert into t_travelistrest(c_invid,c_json) values(?,?)",key,jsonString])
    {
        NSLog(@"insert success");
    }
    [db close];
}

+(void)deleteTraveListRest:(NSString*)invid withDatabase:(FMDatabase*)db
{
    [db open];
    
    [db executeUpdate:@"delete from t_travelistrest where c_invid=?",invid];
    [db close];
}

+ (void)updateTraveListRest:(NSString *)invid andNewJsonString:(NSString *)newString andDataBase:(FMDatabase *)db{
    [db open];
    [db executeUpdate:@"update t_travelistrest set c_json=? where c_invid=?",newString,invid];
    [db close];
}
+ (NSString *)getJsonStringWithInvid:(NSString *)invid andDatabase:(FMDatabase *)db{
    [db open];
    FMResultSet *s=[db executeQuery:@"select * from t_travelistrest where c_invid=?",invid];
    NSString *state;
    while ([s next]) {
        state=[s stringForColumn:@"c_json"];
    }
    [db close];
    return state;
}

+ (NSMutableArray *)getAllInvdidArrayWithDataBase:(FMDatabase *)db{
    NSMutableArray *array=[[NSMutableArray alloc]init];
    [db open];
    FMResultSet * res = [db executeQuery:@"select * from t_travelistrest"];
    while ([res next]) {
        NSString *string=[res stringForColumn:@"c_invid"];
        [array addObject:string];
    }
    [db close];
    return array;

}
@end
